package com.api.component;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.api.model.pojo.HttpResult;

@Component
public class HttpAPIComponent {

//    @Autowired
//    private RequestConfig config;	
    
    /**
     * 支持https访问
     * @return
     */
    public CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				// 信任所有
				@Override
				public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					return true;
				}
			}).build();
			HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}

    /**
     * 不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url) throws Exception {
    	CloseableHttpClient httpClient = createSSLClientDefault();
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);
        // 装载配置信息
//        httpGet.setConfig(config);
        // 发起请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 判断状态码是否为200
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        httpClient.close();
        return null;
    }
    
    
    public HttpEntity doGetByEntity(String url) throws Exception {
    	CloseableHttpClient httpClient = createSSLClientDefault();
    	// 声明 http get 请求
    	HttpGet httpGet = new HttpGet(url);
    	// 装载配置信息
//    	httpGet.setConfig(config);
    	// 发起请求
    	CloseableHttpResponse response = httpClient.execute(httpGet);
    	// 判断状态码是否为200
    	if (response.getStatusLine().getStatusCode() == 200) {
    		// 返回响应体的内容
    		return response.getEntity();
    	}
    	httpClient.close();
    	return null;
    }

    /**
     * 带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
     * @param url
     * @return
     * @throws Exception
     */
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);
        if (map != null) {
            // 遍历map,拼接请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());

    }

    /**
     * 带参数的post请求
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
    	CloseableHttpClient httpClient = createSSLClientDefault();
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
//        httpPost.setConfig(config);
        // 判断map是否为空，不为空则进行遍历，封装from表单对象
        if (map != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
            // 把表单放到post里
            httpPost.setEntity(urlEncodedFormEntity);
        }
        // 发起请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpResult httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity(), "UTF-8"));
        httpClient.close();
        return httpResult;
    }
    
    /**
     * post 请求
     * @param url
     * @param objectJson
     * @return
     */
    public String httpPostWithForm(String url, String objectJson) throws Exception {
    	// 表单方式提交
    	List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
    	JSONObject map = JSONObject.parseObject(objectJson);
    	map.forEach((k, v) -> pairList.add(new BasicNameValuePair(k + "", v + "")));
    	
    	CloseableHttpClient httpClient = createSSLClientDefault();
        HttpPost httpPost = new HttpPost(url);
        String respContent = null;
        httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
        HttpResponse resp = httpClient.execute(httpPost);
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            respContent = EntityUtils.toString(he, "UTF-8");
        }
        httpClient.close();
        return respContent;
    }

    /**
     * 不带参数post请求
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url) throws Exception {
        return this.doPost(url, null);
    }

    /**
     * @param token 
     * 调用第三方接口
     * @Title: doPostToJsonByString 
     * @Description: TODO
     * @param @param httpMethodType
     * @param @param url
     * @param @param dataString
     * @param @param headers
     * @param @return 
     * @return String 
     * @throws
     */
	public String doPostToJsonByString(String url,String dataString, Map<String, String> headers) throws Exception {
		// TODO Auto-generated method stub
		CloseableHttpClient httpClient = createSSLClientDefault();
		String result = null;
		HttpPost post = new HttpPost(url);
		if(headers != null && headers.size() > 0){
			headers.forEach((k,v) -> {
				post.setHeader(k, v);
			});
		}
    	StringEntity stringEntity = new StringEntity(dataString, "UTF-8");
        stringEntity.setContentType("application/json");
		post.setEntity(stringEntity);
		HttpResponse resp = httpClient.execute(post);
        if (resp.getStatusLine().getStatusCode() == 200) {
            HttpEntity he = resp.getEntity();
            result = EntityUtils.toString(he, "UTF-8");
        }
		httpClient.close();
		return result;
	}
}